package com.ruoyi.framework.datasource.transaction;


import com.alibaba.druid.pool.xa.DruidXADataSource;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.framework.datasource.DruidConfig;
import com.ruoyi.framework.datasource.MyBatisConfig;
import com.ruoyi.framework.datasource.properties.DruidProperties;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * com.ruoyi.framework.datasource.transaction
 *
 * @author jierui
 * @version v1.0
 * @date 2020/11/10
 * 描述：
 */
@Configuration
public class DataSourceFactory {

    @Autowired
    private MyBatisConfig myBatisConfig;

    @Autowired
    private DruidProperties druidProperties;



    /**
     * sqlSessionTemplate 与 Spring 事务管理一起使用，以确保使用的实际 SqlSession 是与当前 Spring 事务关联的,
     * 此外它还管理会话生命周期，包括根据 Spring 事务配置根据需要关闭，提交或回滚会话
     * @return
     */
    @Bean
    public CustomSqlSessionTemplate sqlSessionTemplate(DataSource dataSource) {
        Map<Object, SqlSessionFactory> sqlSessionFactoryMap = new HashMap<>();
        SqlSessionFactory sqlSessionFactory = null;


        DataSource xaDataSource = DruidConfig.getXaDataSource(druidProperties.dataSource((DruidXADataSource) dataSource),DataSourceType.MASTER.name());
        try {
            sqlSessionFactory = myBatisConfig.createSqlSessionFactory(xaDataSource);
        } catch (Exception e) {
            e.printStackTrace();
        }
        sqlSessionFactoryMap.put(DataSourceType.MASTER.name(),sqlSessionFactory);
        CustomSqlSessionTemplate customSqlSessionTemplate = new CustomSqlSessionTemplate(sqlSessionFactory);
        customSqlSessionTemplate.setTargetSqlSessionFactories(sqlSessionFactoryMap);
        customSqlSessionTemplate.setDefaultTargetSqlSessionFactory(sqlSessionFactory);
        return customSqlSessionTemplate;
    }


}
